package lv.accenture.ex06;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExtractor implements IExtractor {
	
	public Bookmark bm;
	
	public List<Bookmark> extractBookmarks(String resource) throws IOException {
		List<Bookmark> result = new ArrayList<Bookmark>();
		FileResourceReader reader = new FileResourceReader();
		List<String> lines = reader.readLines(resource);
		
		byte status = 0;		
		
		for (int i = 0; i < lines.size(); i++) {
			String line = lines.get(i);
			
			Pattern p0;
			Matcher m0;
			
			if (status == 0) {
				bm = new Bookmark();
				p0 = Pattern.compile("<item rdf:about=\"([^\"]+)\">");			
				
				m0 = p0.matcher(line);
				if (m0.matches()) {					
					
					String url = m0.group(1);
					
					bm.setUrl(url);
					
					bm.setUid(Integer.toHexString(url.hashCode()));

					status++;
				}	
			}
			else if (status == 1) {
				p0 = Pattern.compile("<title>([^\"]+)</title>");			
				
				m0 = p0.matcher(line);
				
				if (m0.matches()) {
					String title = m0.group(1);
					
					bm.setTitle(title);

					status++;
				}					
			}
			else if (status == 2) {
				p0 = Pattern.compile("<description>([^\"]+)</description>");			
				
				m0 = p0.matcher(line);
				
				if (m0.matches()) {
					String desc = m0.group(1);

					bm.setDescription(desc);
				}
				status++;				
			}
			else if (status == 3) {  
				p0 = Pattern.compile("<dc:creator>([^\"]+)</dc:creator>");			
				
				m0 = p0.matcher(line);
				
				if (m0.matches()) {
					String creator = m0.group(1);
					
					bm.setCreator(creator);

					status++;
				}
			}
			else if (status == 4) {
				p0 = Pattern.compile("<dc:date>([^\"]+)</dc:date>");			
				
				m0 = p0.matcher(line);
				
				if (m0.matches()) {
					String date = m0.group(1);
					
					String[] year = date.split("-");
					
					bm.setYear(year[0]);

					status++;
				}
			}							
			else if (status == 5) {
				
				p0 = Pattern.compile("<dc:subject>([^\"]+)</dc:subject>");			
				
				m0 = p0.matcher(line);
				
				if (m0.matches()) {
					String subjects = m0.group(1);
					
					String[] subject = subjects.split(" ");
					
					List<String> tags = new ArrayList();
					
					for (int j=0; j<subject.length; j++) {
						tags.add(subject[j]);
					}					
					bm.setTags(tags);
				

				}

				result.add(bm);
				
				status = 0;
				
			}
			
		}

		return result;
		
	}

}
